//
//  SLApplyLoacnViewController.m
//  SecondLoan
//
//  Created by Echo Zhangjie on 2019/9/1.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "SLApplyLoacnViewController.h"
#import "SLProductApplyTitleCellTableViewCell.h"
#import "SLProductInfoJineTableViewCell.h"
#import "SLProductInfoSelectTableViewCell.h"
#import "SLProductRateTableViewCell.h"
#import "WebSocketManager.h"
#import "SLSingleChoseView.h"
#import "SLVerifySubmitViewController.h"
#import "CommonModelTypeDIc.h"
#import "ProductDetailModel.h"

@interface SLApplyLoacnViewController () <UITableViewDelegate, UITableViewDataSource, SLProductInfoSelectTableViewCellDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger borrowMoney;
@property (nonatomic, assign) double borrowRate;
@property (nonatomic, assign) NSInteger borrowTerm;
@property (nonatomic, assign) NSInteger payMethod;
@property (nonatomic, strong) NSString *token;

@property (strong, nonatomic) SLProductInfoJineTableViewCell *moneyCell;
@property (strong, nonatomic) SLProductRateTableViewCell *rateCell;

@property (strong, nonatomic) ProductDetailModel *model;
@property (nonatomic, copy) NSString *maxQuota;         //最高额度

@end

@implementation SLApplyLoacnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"贷款申请";
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupTableView];
    [self setupSubmitBtn];
    [self loadData];
}

- (void)loadData
{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [param setObject:self.productId forKey:@"productId"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_product_info) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        if (!error) {
            self.model = [ProductDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
            self.maxQuota = [NSString stringWithFormat:@"%ld",self.model.maxQuota];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame: CGRectMake(0, KStatusBarAndNavigationBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - KStatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"SLProductApplyTitleCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"SLProductApplyTitleCellTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SLProductInfoJineTableViewCell" bundle:nil] forCellReuseIdentifier:@"SLProductInfoJineTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SLProductInfoSelectTableViewCell" bundle:nil] forCellReuseIdentifier:@"SLProductInfoSelectTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SLProductRateTableViewCell" bundle:nil] forCellReuseIdentifier:@"SLProductRateTableViewCell"];
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
}

- (void)setupSubmitBtn {
    self.view.fsBackGroundColor(0xffffff).develop(^(FFactory * factory){
        factory.button().fsBackGroundImage(@"btn_bg").fsFontSize(20.0).fsText(@"提交申请").fsTextColor(0xffffff).fsOnClick(submitApply:).fsClip(YES).fsRadius(3.3).fsFvid(@"submitBtn");
    });
    [fQuery(self.view, @"submitBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-(KMagrinBottom + 10));
        make.left.equalTo(self.view).with.mas_offset(10);
        make.right.equalTo(self.view).with.mas_offset(-10);
        make.height.equalTo(@50);
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    if (indexPath.row == 1) {
        self.borrowMoney = [textField.text integerValue];
    } else if (indexPath.row == 3) {
      self.borrowRate = [textField.text doubleValue];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    if (indexPath.row == 1) {
        BOOL isHaveDian = YES;
        if ([textField.text rangeOfString:@"."].location == NSNotFound){
            isHaveDian = NO;
        }
        if ([string length] > 0){
            unichar single = [string characterAtIndex:0];//当前输入的字符
            if ((single >= '0' && single <= '9') || single == '.')//数据格式正确
            {
                //首字母不能为0和小数点
                if([textField.text length] == 0){
                    if(single == '.'){
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                    if (single == '0'){
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }
                //输入的字符是否是小数点
                if (single == '.')
                {
                    if(!isHaveDian)//text中还没有小数点
                    {
                        isHaveDian = YES;
                        return YES;
                    }else{
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }else{
                    if (isHaveDian) {//存在小数点
                        //判断小数点的位数
                        NSRange ran = [textField.text rangeOfString:@"."];
                        if (range.location - ran.location <= 2) {
                            return YES;
                        }else{
                            return NO;
                        }
                    }else{
                        return YES;
                    }
                }
            }else{//输入的数据格式不正确
                [textField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
        }
    }
    if (indexPath.row == 3) {
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if ([toBeString doubleValue] > 36) {
            return NO;
        }
        BOOL isHaveDian = YES;
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            isHaveDian=NO;
        }
        if ([string length]>0) {
            unichar single=[string characterAtIndex:0];//当前输入的字符
            if ((single >='0' && single<='9') || single=='.') {//数据格式正确
                //首字母不能为小数点
                if([textField.text length]==0) {
                    if(single == '.') {
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }
                if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){
                    if(single != '.'){
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }
                if (single=='.') {
                    if(!isHaveDian) {//text中还没有小数点
                        isHaveDian=YES;
                        return YES;
                    }else {
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }else {
                    if (isHaveDian)//存在小数点
                    {
                        //判断小数点的位数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        NSInteger tt=range.location-ran.location;
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else {
                        if (textField.text.length > 5) {
                            return NO;
                        }
                        return YES;
                    }
                }
            }else{//输入的数据格式不正确
                [textField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
        }else {
            return YES;
        }
    }

    return YES;
}

#pragma mark ==== UITableView ======
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        SLProductApplyTitleCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProductApplyTitleCellTableViewCell" forIndexPath:indexPath];
        return cell;
    }else if (indexPath.row == 1){
        SLProductInfoJineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProductInfoJineTableViewCell" forIndexPath:indexPath];
        self.borrowMoney = [cell getJine];
        [cell setTextFieldDelegate: self];
        [cell setActionDelegate:self action:@selector(textFieldEditChanged:)];
        self.moneyCell = cell;
        return cell;

    }else if (indexPath.row == 2){
        SLProductInfoSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProductInfoSelectTableViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        [cell setTitle: @"贷款期限"];
        cell.type = SelectCellTypeTerm;
        return cell;
    }else if (indexPath.row == 3){
        SLProductRateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProductRateTableViewCell" forIndexPath:indexPath];
        [cell setTextFieldDelegate: self];
        self.rateCell = cell;
        return cell;
    } else if (indexPath.row == 4){
      SLProductInfoSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProductInfoSelectTableViewCell" forIndexPath:indexPath];
      cell.delegate = self;
      cell.type = SelectCellTypeMethod;
      [cell setTitle: @"还款方式"];
      return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.row == 2){

  }
}

- (void)textFieldEditChanged:(UITextField *)textField
{
    if (textField.text.integerValue > self.maxQuota.integerValue) {
        [self HUDshowErrorWithStatus:[NSString stringWithFormat:@"您最多可贷款%@元",self.maxQuota]];
        textField.text = nil;
    }
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

    //MARK: 提交申请
- (void)submitApply:(UIButton *)sender {
    if (self.borrowMoney <= 0) {
        [self HUDshowErrorWithStatus:@"请正确填写贷款金额"];
        return;
    } else if (self.borrowMoney > self.maxQuota.integerValue) {
        [self HUDshowErrorWithStatus:[NSString stringWithFormat:@"您最多可贷款%@元,请重新填写金额",self.maxQuota]];
        return;
    } else if (self.borrowTerm < 1) {
        [self HUDshowErrorWithStatus:@"请选择贷款期限"];
        return;
    } else if (self.borrowRate <= 0) {
      [self HUDshowErrorWithStatus:@"请正确填写期望借款利率"];
        return;
    } else if (self.payMethod <= 0){
        [self HUDshowErrorWithStatus:@"请选择还款方式"];
        return;
    }
    sender.enabled = NO;
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"token"] = [[[UserLocal sharedInstance] currentUserInfo] token];
    param[@"loanMoney"] = @(self.borrowMoney);
    param[@"productId"] = self.productId;
    param[@"loanTerm"] = @(self.borrowTerm);
    param[@"rate"] = [NSString stringWithFormat:@"%.2f%%", self.borrowRate];
    param[@"paybackTYPE"] = @(self.payMethod);
//    param[@"guarantyType"] = @(self.payMethod);
    [self HUDshowWithStatus:@""];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_loan_apply_normal) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [self HUDdismiss];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            sender.enabled = YES;
//        });
        if (!error) {
//            [self HUDshowSuccessWithStatus:@"提交成功"];
            SLVerifySubmitViewController *vsVC = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
            [self.navigationController pushViewController:vsVC animated:YES];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
    }];
}

- (NSString *)periodLoan:(NSInteger)term
{
    NSString *strTerm = @"";
    if (term == 1) {
        strTerm = @"3个月";
    }else if (term == 2){
        strTerm = @"6个月";
    }else if (term == 3){
        strTerm = @"12个月";
    }else if (term == 4){
        strTerm = @"24个月";
    }else if (term == 5){
        strTerm = @"36个月";
    }
    return strTerm;
}

#pragma mark ----- SLProductInfoSelectTableViewCellDelegate --
- (void)showOptionsOnView: (SLProductInfoSelectTableViewCell *)targetView {
    [self.moneyCell.jineTextField endEditing:YES];
    [self.rateCell.expRateField endEditing:YES];
    switch (targetView.type) {
        case SelectCellTypeTerm:
        {
            // 如果非已婚
            NSMutableArray *arrLoanTerm = [NSMutableArray array];
            for (NSDictionary *dic in [CommonModelTypeDIc shareManager].arrayLoanTerm) {
                NSString *loanTerm = dic[@"name"];
                if (loanTerm != nil) {
                    NSInteger loanI  = [[loanTerm stringByReplacingOccurrencesOfString:@"个月" withString:@""] integerValue];
                    NSInteger loanMax = [[[self periodLoan:self.model.loanTerm] stringByReplacingOccurrencesOfString:@"个月" withString:@""] integerValue];
                    if( loanI <= loanMax){
                        [arrLoanTerm addObject:dic];
                    }
                }
            }
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:arrLoanTerm title:@"选择期限"] ;
            [view setEnterWhichRowBlock:^(NSString * iterm, NSString * _Nonnull rowId, NSInteger whichRow) {
                [targetView setItem:iterm];
                self.borrowTerm = [rowId integerValue];
            }];
            [view popTo:nil];
        }
            break;
        default:
        {
            SLSingleChoseView * view = [[SLSingleChoseView alloc] initWithFrame:CGRectZero data:[CommonModelTypeDIc shareManager].arrayPaybackType title:@"选择方式"];
            [view setEnterWhichRowBlock:^(NSString * iterm, NSString * _Nonnull rowId, NSInteger whichRow) {
                self.payMethod = [rowId integerValue];
                [targetView setItem:iterm];
            }];
            [view popTo:nil];
        }
            break;
    }
}
@end
